const axios = require('axios');
const cheerio = require('cheerio');
const fs = require('fs');
const path = require('path');
const readline = require('readline');

class ListGenerator {
    constructor() {
        this.defaultHeaders = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "priority": "u=0, i",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\"",
            "sec-fetch-dest": "document",
            "sec-fetch-mode": "navigate",
            "sec-fetch-site": "same-origin",
            "sec-fetch-user": "?1",
            "upgrade-insecure-requests": "1"
        };
    }

    async searchMovie(movieName) {
        try {
            const searchUrl = `https://www.themoviedb.org/search?query=${encodeURIComponent(movieName)}`;
            console.log(`🔍 搜索电影: ${movieName}`);

            const response = await axios.get(searchUrl, {
                headers: this.defaultHeaders
            });

            const $ = cheerio.load(response.data);
            
            // 根据分析，搜索结果在 div.search_results.movie > div 中
            const movieResults = $('div.search_results.movie > div > div');
            const results = [];

            movieResults.each((_, elem) => {
                const $elem = $(elem);
                // 查找 a.result 链接
                const $link = $elem.find('a.result');
                if ($link.length > 0) {
                    const href = $link.attr('href');
                    const title = $link.find('h2').text().trim();
                    const year = $link.find('.release_date').text().trim();
                    
                    if (href && title) {
                        results.push({
                            title: title,
                            year: year,
                            url: `https://www.themoviedb.org${href}`
                        });
                    }
                }
            });

            console.log(`   找到 ${results.length} 个搜索结果`);
            return results;
        } catch (error) {
            console.error(`❌ 搜索电影 "${movieName}" 时出错:`, error.message);
            return [];
        }
    }

    async getUserChoice(movieName, results) {
        return new Promise((resolve) => {
            const rl = readline.createInterface({
                input: process.stdin,
                output: process.stdout
            });

            console.log(`\n📋 "${movieName}" 找到多个匹配结果:`);
            results.forEach((result, index) => {
                console.log(`   ${index + 1}. ${result.title} ${result.year ? `(${result.year})` : ''}`);
            });
            console.log(`   0. 跳过此电影`);

            rl.question(`\n请选择对应的电影 (1-${results.length}, 0=跳过): `, (answer) => {
                rl.close();
                const choice = parseInt(answer);
                resolve(choice);
            });
        });
    }

    async generateList(moviesDir) {
        try {
            console.log(`📁 开始扫描电影文件夹: ${moviesDir}`);
            
            // 检查文件夹是否存在
            if (!fs.existsSync(moviesDir)) {
                console.error(`❌ 错误: 文件夹不存在: ${moviesDir}`);
                return;
            }

            // 读取所有子文件夹
            const items = fs.readdirSync(moviesDir, { withFileTypes: true });
            const movieFolders = items.filter(item => item.isDirectory()).map(item => item.name);
            
            if (movieFolders.length === 0) {
                console.log(`⚠️  未找到任何子文件夹`);
                return;
            }

            console.log(`📂 找到 ${movieFolders.length} 个电影文件夹`);
            console.log(`电影列表: ${movieFolders.join(', ')}`);
            
            const listEntries = [];
            
            for (let i = 0; i < movieFolders.length; i++) {
                const movieName = movieFolders[i];
                console.log(`\n[${i + 1}/${movieFolders.length}] 处理: ${movieName}`);
                
                // 搜索电影
                const searchResults = await this.searchMovie(movieName);
                
                if (searchResults.length === 0) {
                    console.log(`❌ 未找到 "${movieName}" 的搜索结果`);
                    continue;
                } else if (searchResults.length === 1) {
                    // 只有一个结果，直接使用
                    const result = searchResults[0];
                    console.log(`✅ 自动匹配: ${result.title} ${result.year ? `(${result.year})` : ''}`);
                    listEntries.push(`${movieName}||${result.url}`);
                } else {
                    // 多个结果，需要用户选择
                    const choice = await this.getUserChoice(movieName, searchResults);
                    
                    if (choice > 0 && choice <= searchResults.length) {
                        const selectedResult = searchResults[choice - 1];
                        console.log(`✅ 用户选择: ${selectedResult.title} ${selectedResult.year ? `(${selectedResult.year})` : ''}`);
                        listEntries.push(`${movieName}||${selectedResult.url}`);
                    } else {
                        console.log(`⏭️  跳过: ${movieName}`);
                    }
                }
                
                // 添加延迟，避免请求过于频繁
                if (i < movieFolders.length - 1) {
                    console.log('⏳ 等待 1 秒...');
                    await new Promise(resolve => setTimeout(resolve, 1000));
                }
            }
            
            // 生成 List.txt 文件
            if (listEntries.length > 0) {
                const listFilePath = path.join(moviesDir, 'List.txt');
                const listContent = listEntries.join('\n');
                fs.writeFileSync(listFilePath, listContent, 'utf8');
                
                console.log(`\n🎉 List.txt 已生成: ${listFilePath}`);
                console.log(`📝 包含 ${listEntries.length} 部电影:`);
                listEntries.forEach(entry => {
                    const [name] = entry.split('||');
                    console.log(`   - ${name}`);
                });
            } else {
                console.log(`\n⚠️  没有找到任何有效的电影匹配，未生成 List.txt`);
            }
            
        } catch (error) {
            console.error('❌ 生成 List.txt 时出错:', error.message);
        }
    }
}

// 主函数
async function main() {
    const args = process.argv.slice(2);
    
    if (args.length !== 1) {
        console.log('🎬 TMDb 电影清单生成器');
        console.log('');
        console.log('使用方法:');
        console.log('  node createlist.js <电影文件夹路径>');
        console.log('');
        console.log('示例:');
        console.log('  node createlist.js "D:\\Movies"');
        console.log('  node createlist.js "G:\\m"');
        console.log('');
        console.log('说明:');
        console.log('  - 脚本会扫描指定文件夹下的所有子文件夹');
        console.log('  - 每个子文件夹名称作为电影名进行搜索');
        console.log('  - 自动匹配唯一结果，多个结果时提示用户选择');
        console.log('  - 生成的 List.txt 可用于批量处理电影信息');
        return;
    }
    
    const moviesDir = args[0];
    const generator = new ListGenerator();
    await generator.generateList(moviesDir);
}

// 如果直接运行此文件，则执行主函数
if (require.main === module) {
    main().catch(error => {
        console.error('程序执行失败:', error.message);
        process.exit(1);
    });
}

module.exports = ListGenerator;
